package controle;

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import org.apache.commons.fileupload.*; 
import org.apache.commons.fileupload.servlet.*; 
import org.apache.commons.fileupload.disk.*; 
import java.util.List; 
import java.util.Iterator; 
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

/**
 * Servlet implementation class Upload
 */
@WebServlet("/Upload")
public class Upload extends HttpServlet { 

public void init() throws ServletException { 
super.init(); 

} 

public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws IOException, ServletException{ 

response.setContentType("text/html; charset=ISO-8859-1"); 
PrintWriter out = response.getWriter(); 

String path = getServletContext().getRealPath("imagem"); 



DiskFileItemFactory factory = new DiskFileItemFactory(); 
ServletFileUpload sfu = new ServletFileUpload(factory); 

try { 

List list = sfu.parseRequest(request); 
Iterator iterator = list.iterator(); 

while(iterator.hasNext()){ 
FileItem item = (FileItem)iterator.next(); 

if (!item.isFormField()){ 
String filename = item.getName(); 

if ((filename != null) && (!filename.equals(""))){ 
filename = (new File(filename)).getName(); 
item.write(new File(path + "/" + filename)); 
} 

out.println("<p>"); 
out.println("Nome do arquivo:"); 
out.println("<strong>"); 
out.println(item.getName() + 
"</strong><br />"); 
out.println(path + "\\" + filename); 
out.println("</p>"); 


} 
} 

}catch (FileUploadException e) { 
e.printStackTrace(); 
}catch (Exception e) { 
e.printStackTrace(); 
} 

} 
public void destroy() { 
super.destroy(); 
} 

} 	